<?php
/**
 * jishupu-cms
 * @Author:技术铺<jishupu@qq.com>
 * @Date: 2022/3/16
 */

namespace App\Services;

use App\Models\Ads;
use App\Models\AdsSpace;
use Carbon\Carbon;
use Illuminate\Support\Facades\Redis;

/**
 * 广告模块服务层
 *
 * Class AdsService
 * @package App\Services
 */
class AdsService
{

    /**
     * 根据广告位ID获取广告位列表
     * @param int $space_id
     * @param int $num
     * @return array|\Illuminate\Support\Collection
     */
    static function getAdsBySpaceId($space_id = 0, $num = 0)
    {
        if (!$space_id) return [];
        $space = AdsSpace::where([['id', $space_id], ['status', 1]])->first();
        if (!$space) return [];
        $query = $space->ads()->where('status', 1)->where(function ($query) {
            $query->where('cast_period', 1);
            $query->orWhere([
                ['cast_period', 2],
                ['start_time', '<=', Carbon::now()],
                ['end_time', '<', Carbon::now()]
            ]);
        });
        if ($num > 0) {
            $query = $query->limit($num);
        }
        $result = $query->get();
        $cover_image_ids = Ads::where([['space_id', $space_id], ['status', 1]])->where(function ($query) {
            $query->where('cast_period', 1);
            $query->orWhere([
                ['cast_period', 2],
                ['start_time', '<=', Carbon::now()],
                ['end_time', '<', Carbon::now()]
            ]);
        })->pluck('cover_image');
        $getCoverImage = AttachmentService::previewList($cover_image_ids);
        $setCoverImage = [];
        collect($getCoverImage)->each(function ($item) use (&$setCoverImage, &$resetData) {
            $setCoverImage[$item['id']] = $item;
        });
        return collect($result)->each(function (&$item) use ($setCoverImage) {
            $item['image_url'] = AttachmentService::getDefaultImageUrl();
            if (isset($setCoverImage[$item['cover_image']]['url'])) {
                $item['image_url'] = $setCoverImage[$item['cover_image']]['url'];
            }
            // link
            self::setAdsLink($item);
        });
    }

    /**
     * 根据广告位标识名称获取广告位列表
     * @param string $id_name
     * @param int $num // 数量
     * @return array|\Illuminate\Support\Collection
     */
    static function getAdsBySpaceIdName($id_name = "", $num = 0)
    {
        if (!$id_name) return [];
        $space = AdsSpace::where([['id_name', $id_name], ['status', 1]])->first();
        if (!$space) return [];
        return self::getAdsBySpaceId($space->id, $num);
    }

    /**
     * 根据广告位关联栏目ID获取广告位列表
     * @param int $cate_id // 栏目ID
     * @param int $num
     * @return array|\Illuminate\Support\Collection
     */
    static function getAdsByInfoCategoryId($cate_id = 0, $num = 0)
    {
        if (!$cate_id) return [];
        $space = AdsSpace::where([['info_category_id', $cate_id], ['status', 1]])->first();
        if (!$space) return [];
        return self::getAdsBySpaceId($space->id, $num);
    }

    /**
     * 设置广告链接相关属性
     * @param $item
     */
    static function setAdsLink(&$item = null)
    {
        if ($item != null) {
            $item['href_'] = $item['href'] ? " href =${item['href']} " : '';
            $item['href_target_'] = $item['href_target'] ? " target =${item['href_target']} " : '';
            $item['rel_'] = $item['rel'] ? " rel =${item['rel']} " : '';
        }
    }

    /**
     * 【作废保留】更新广告状态待处理清单
     * 说明：通过redis发布/订阅频道进行处理
     */
/*    static function updateAdsStatusList()
    {
        $ads_status_list = Ads::where([['cast_period', 2], ['cast_status', '<>', 2]])->get();
        collect($ads_status_list)->each(function ($item) {
            Redis::hSet('ads_status_list', $item->id, json_encode(['start_time' => $item->start_time, 'end_time' => $item->end_time, 'cast_status' => $item->cast_status]));
        });
    }*/

    /**
     * 【作废保留】更新广告状态
     */
/*    static function updateAdsStatus()
    {
        $ads_status_list = Redis::hGetAll('ads_status_list');
        $updateData = [];
        $clearData = [];
        collect($ads_status_list)->each(function ($item, $id) use (&$updateData, &$clearData) {
            $content = json_decode($item, true);
            // 判断投放状态
            $start_time = carbon::parse($content['start_time']);
            $end_time = carbon::parse($content['end_time']);
            $now = Carbon::now();
            $cast_status = 0;
            if ($now->gte($start_time) && $now->lt($end_time)) {
                // 当前时间>=开始时间 且 < 结束时间 ：已投放
                $cast_status = 1;
            } else if ($now->gte($end_time)) {
                // 当前时间 >= 结束时间：已过期
                $cast_status = 2;
            }
            if ($cast_status > $content['cast_status']) {
                $needUpdateData = ['id' => $id, 'cast_status' => $cast_status];
                $updateData[] = $needUpdateData;
                if ($cast_status == 2) {
                    $clearData[] = $needUpdateData;
                }
            }
        });
        // 更新数据库
        if (!empty($updateData)) {
            $ads = new Ads();
            if ($ads->batchUpdate($updateData)) {
                // 更新待处理清单中的广告投放状态
                collect($updateData)->each(function ($item) {
                    if ($item['cast_status'] == 1) {
                        $content = Redis::hGet('ads_status_list', $item['id']);
                        $content = json_decode($content, true);
                        $content['cast_status'] = 1;
                        Redis::hSet('ads_status_list', $item['id'], json_encode($content));
                    }
                });
                // 清空已过期的key
                collect($clearData)->each(function ($item) {
                    Redis::hDel('ads_status_list', $item['id']);
                });
            }
        }
    }*/


}
